package com.czk.webflux.handler;

import com.czk.webflux.entity.User;
import com.czk.webflux.servcie.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * 函数式编程
 * 需要自己初始化服务器，编写router
 *
 * @Author:ChenZhangKun
 * @Date: 2020/11/26 21:31
 */
public class UserHandler {
    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    public Mono<ServerResponse> getUserById(ServerRequest request) {
        // 从路径得到id
        String id = request.pathVariable("id");
        Integer userId = Integer.parseInt(id);
        // 空值处理
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();
        // 拿到结果
        Mono<User> monoUser = this.userService.findUserById(userId);
        // 吧monoUser进行转换返回
        // 使用Reactor的操作符flatMap
        Mono<ServerResponse> serverResponseMono = monoUser.flatMap(person -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(fromObject(person)))
                .switchIfEmpty(notFound);
        return serverResponseMono;
    }

    public Mono<ServerResponse> getAllUser(ServerRequest request) {
        Flux<User> allUser = this.userService.findAllUser();
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(allUser, User.class);
    }

    public Mono<ServerResponse> saveUser(ServerRequest request) {
        // 拿到user
        Mono<User> userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().build(this.userService.saveUserInfo(userMono));
    }
}
